<template>
  <el-drawer
    title="功能权限分配"
    size="300px"
    :wrapperClosable="false"
    :visible="dialogVisible"
    append-to-body
    @close="close"
  >
    <div v-loading="wrapperLoading" class="draw-wrapper loading-wrapper">
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        node-key="id"
        :props="{
          children: 'childList',
          label: 'name',
        }"
        :default-expanded-keys="defaultExpandedKeys"
        :default-checked-keys="checkedKeys"
      />

      <div class="mt10" flex="dir:right">
        <el-button type="primary" :loading="btnLoading" @click="submitData">确定</el-button>
        <el-button class="mr10" @click="close">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import dialogMixin from "mixins/dialogMixin";
import { MenuAppTree } from "api/sys/menu";
import { isNumber } from "lodash";
import { RoleMenuPermBatch, RoleMenuPerm } from "api/sys/role";

export default {
  mixins: [dialogMixin],
  props: {
    // 当前行数据(最上级)
    currentRowObj: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      treeData: [],
      // 默认展开数据
      defaultExpandedKeys: [],
      // 选中的数据
      checkedKeys: [],
    };
  },
  methods: {
    /**
     * 初始化
     */
    initForm() {
      this._MenuAppTree();
    },
    /**
     * 获取应用菜单树
     */
    async _MenuAppTree() {
      try {
        this.wrapperLoading = true;
        const data = await MenuAppTree();
        if (data) {
          const tempData = this.treeDataFormat(data);
          this.treeData = tempData;
          this.defaultExpandedKeys = this.setDefaultExpandedKeys(tempData);

          // 设置被选中的默认值
          const [roleMenuData] = await Promise.all([this._RoleMenuPerm()]);
          this.checkedKeys = roleMenuData;
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.wrapperLoading = false;
      }
    },

    /**
     * 获取详情
     */
    async _RoleMenuPerm() {
      try {
        const data = await RoleMenuPerm(this.currentRowObj.id);
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 设置默认展开数据
     */
    setDefaultExpandedKeys(arr) {
      let tempArr = [];
      arr.map((item) => {
        tempArr.push(item.id);
      });
      return tempArr;
    },
    /**
     * 树形数据格式化
     */
    treeDataFormat(arr) {
      arr.map((item) => {
        const { childList } = item;
        if (childList) {
          this.changeItemId({ arr: childList, topId: item.id });
        }
      });
      // TODO: 这里还没做完
      return arr.sort((a, b) => a.sortBy - b.sortBy);
    },
    /**
     * 改变数据的id
     */
    changeItemId({ arr, topId }) {
      arr.map((item) => {
        const { childList } = item;
        if (childList && childList.length) {
          this.changeItemId({ arr: childList, topId });
        }
      });
    },
    /**
     * 获取选中的数据
     */
    getCheckedKeysFromDetails(roleMenuList) {
      let tempArr = [];
      roleMenuList.map((item) => {
        const { menuIdList } = item;
        tempArr.push(...menuIdList.map((menuId) => menuId));
      });
      return tempArr;
    },

    async submitData() {
      try {
        this.btnLoading = true;
        const checkKeys = this.$refs.tree.getCheckedKeys(true);
        if (!checkKeys.length) return this.$message.error("请选择功能权限");
        await RoleMenuPermBatch({ id: this.currentRowObj.id, menuIds: checkKeys });
        this.$message.success("功能权限配置成功");
        this.$emit("success");
        this.close();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 选择的数据格式化
     */
    checkKeysFormat(checkKeys) {
      let obj = {};
      checkKeys.map((item) => {
        const arr = item.split("-");
        if (!obj[arr[0]]) {
          obj[arr[0]] = [];
        }
        if (arr[1]) {
          obj[arr[0]].push(arr[1]);
        } else {
          obj[arr[0]].push(Number(arr[0]));
        }
      });
      return this.getParamsData(obj);
    },
    /**
     * 获取
     */
    getParamsData(obj) {
      let roleMenuList = [];
      let affiliationAppTypeList = [];
      Object.keys(obj).map((item) => {
        let tempArr = obj[item];
        const tempId = tempArr.find((item) => isNumber(item));
        if (tempId !== undefined) {
          affiliationAppTypeList.push(tempId);
        } else {
          roleMenuList.push({
            affiliationAppType: item,
            menuIdList: obj[item],
          });
        }
      });
      return { affiliationAppTypeList, roleMenuList };
    },
  },
};
</script>
